package com.tebiecloud.uaa.admin.server.service.impl;

import com.tebiecloud.base.client.constants.BaseConstants;
import com.tebiecloud.base.client.model.UserAccount;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.security.oauth2.client.OAuth2ClientProperties;
import com.tebiecloud.common.utils.JsonUtils;
import com.tebiecloud.common.utils.WebUtils;
import com.tebiecloud.uaa.admin.server.service.feign.BaseUserServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: tebie
 * @Date: 2019-08-10 08:59
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private BaseUserServiceClient baseUserServiceClient;
    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String, String> parameterMap = WebUtils.getParameterMap(WebUtils.getHttpServletRequest());
        log.info("xiaoc>> 登录参数：{}", JsonUtils.Obj2Str(parameterMap));
        //优先设置attribute
        String newUsername = WebUtils.getAttributeMap("username")==null?username:WebUtils.getAttributeMap("username");
        String newPassword = WebUtils.getAttributeMap("password")==null?parameterMap.get("password"):WebUtils.getAttributeMap("password");
        String type = WebUtils.getAttributeMap("type")==null?parameterMap.get("type"):WebUtils.getAttributeMap("type");
        ResultBody<UserAccount> resp = baseUserServiceClient.getUserAccountForLogin(newUsername,newPassword,type);
        if (resp.getCode() != ResultEnum.OK.getCode() || resp.getData() == null) {
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        UserAccount account = resp.getData();
        String domain = account.getDomain();
        Long accountId = account.getAccountId();
        Long userId = account.getUserId();
        String password = account.getPassword();
        String nickName = account.getNickName();
        String avatar = account.getAvatar();
        String accountType = account.getAccountType();
        boolean accountNonLocked = account.getStatus().intValue() != BaseConstants.ACCOUNT_STATUS_LOCKED;
        boolean credentialsNonExpired = true;
        boolean enabled = account.getStatus().intValue() == BaseConstants.ACCOUNT_STATUS_NORMAL ? true : false;
        boolean accountNonExpired = true;
        SecurityUserDetails userDetails = new SecurityUserDetails();
        userDetails.setDomain(domain);
        userDetails.setAccountId(accountId);
        userDetails.setUserId(userId);
        userDetails.setUsername(username);
        userDetails.setPassword(password);
        userDetails.setNickName(nickName);
        userDetails.setAuthorities(account.getAuthorities());
        userDetails.setAvatar(avatar);
        userDetails.setAccountNonLocked(accountNonLocked);
        userDetails.setAccountNonExpired(accountNonExpired);
        userDetails.setAccountType(accountType);
        userDetails.setCredentialsNonExpired(credentialsNonExpired);
        userDetails.setEnabled(enabled);
        userDetails.setClientId(oAuth2ClientProperties.getOauth2().get("admin").getClientId());
        return userDetails;
    }

//    /**
//     * 生成测试的认证用户
//     * @return
//     */
//    public static SecurityClient createTestUser() {
//        long userId = 1;
//        String username = "test";
//        String password = "$2a$10$ORbKCTcBkWn3wzEWK9j6ZeVHnQ7k6zbyZjgY2o5b892fPraSs0RsC";
//        List<GrantedAuthority> authorities = Lists.newArrayList();
//        SecurityAuthority securityAuthority = new SecurityAuthority();
//        securityAuthority.setAuthority("a-authority");
//        securityAuthority.setAuthorityId("a-id");
//        securityAuthority.setOwner("xiaoc");
//        securityAuthority.setExpireTime(new Date(System.currentTimeMillis() + 1000000));
//        authorities.add(securityAuthority);
//        boolean accountNonLocked = true;
//        boolean accountNonExpired = true;
//        boolean enabled = true;
//        boolean credentialsNonExpired = true;
//        String clientId = "1552274783265";
//        String domain = "localhost";
//        String nickName = "test";
//        String avatar = "http://~~";
//        return new SecurityUser(userId, username, password, authorities, accountNonLocked, accountNonExpired, enabled, credentialsNonExpired, clientId, domain, nickName, avatar);
//    }

}
